/*
 * Copyright 2018 Youchaoshi authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common.base.activity;

import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import common.base.dialog.PubDialogLoading;
import common.base.interfaces.ViewInterface;
import common.tool.StatusBarUtil;
import es.dmoral.toasty.Toasty;
import common.tool.MySharedPreference;
import common.tool.NetBroadcastReceiver;
import common.tool.NetUtil;
import common.tool.RequestPer;

import static common.base.enums.PubDialogLoadingEnum.全屏显示;

/**
 *  基类文件
 * Created by JustTong on 2018/12/11.
 */
public abstract class BaseActivity extends AppCompatActivity implements NetBroadcastReceiver.NetEvent, ViewInterface {

    public BaseActivity activity = this;
    Unbinder unbinder;
    public static NetBroadcastReceiver.NetEvent event;
    /**
     * 加载数据时全屏显示dialog
     */
    public PubDialogLoading loading;
    public Dialog dialog;
    /**
     * 网络类型
     */
    private int netMobile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(setLayout());
        unbinder = ButterKnife.bind(this);
        init();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = activity.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            StatusBarUtil.StatusBarLightMode(activity);
        }


        event = this;
        loading = new PubDialogLoading(this, 全屏显示, false);
        inspectNet();
    }


    public abstract void init();

    public abstract int setLayout();


    /**
     * 初始化时判断有没有网络
     */

    public boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(activity);
        return isNetConnect();
        // if (netMobile == 1) {
        // System.out.println("inspectNet：连接wifi");
        // } else if (netMobile == 0) {
        // System.out.println("inspectNet:连接移动数据");
        // } else if (netMobile == -1) {
        // System.out.println("inspectNet:当前没有网络");
        //
        // }
    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        String last_wifi_type = MySharedPreference.get("wifi_type", "", activity);

        if (netMobile == -1) {
            //断开网络
            Toasty.warning(activity, "请检查网络").show();
            //MyToast.makeText(activity, "请检查网络!");
            MySharedPreference.save("wifi_type", "" + netMobile, activity);

        } else {

            MySharedPreference.save("wifi_type", "" + netMobile, activity);

        }
    }

    /**
     * 判断有无网络 。
     *
     * @return true 有网, false 没有网络.
     */
    public boolean isNetConnect() {
        if (netMobile == 1) {
            return true;
        } else if (netMobile == 0) {
            return true;
        } else if (netMobile == -1) {
            return false;
        }
        return false;
    }

    RequestPer requestPer;

    public void setRequestPer(RequestPer requestPer) {
        this.requestPer = requestPer;
    }

    final int requestCodeNum = 111111;

    public void RequestPermission(String permissionsArray[]) {
        AndPermission.with(this)
                .requestCode(requestCodeNum)
                .permission(permissionsArray)
                .callback(permissionListener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(activity, rationale).show();
                        if (requestPer != null) {
                            requestPer.isPermission(false);
                        }
                    }
                })
                .start();
        return;
    }

    /**
     * 回调监听。
     */
    public PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            switch (requestCode) {
                case requestCodeNum: {
//                    Toast.makeText(activity, R.string.successfully, Toast.LENGTH_SHORT).show();
                    if (requestPer != null) {
                        requestPer.isPermission(true);
                    }
                    break;
                }
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            switch (requestCode) {
                case requestCodeNum: {
//                    Toast.makeText(ListenerActivity.this, R.string.failure, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
            if (requestPer != null) {
                requestPer.isPermission(false);
            }
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(activity, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(activity, 111)
                        .setTitle("权限申请失败")
                        .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                        .setPositiveButton("好，去设置")
                        .show();

                // 第二种：用自定义的提示语。
//             AndPermission.defaultSettingDialog(this, REQUEST_CODE_SETTING)
//                     .setTitle("权限申请失败")
//                     .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
//                     .setPositiveButton("好，去设置")
//                     .show();

//            第三种：自定义dialog样式。
//            SettingService settingService = AndPermission.defineSettingDialog(this, REQUEST_CODE_SETTING);
//            你的dialog点击了确定调用：
//            settingService.execute();
//            你的dialog点击了取消调用：
//            settingService.cancel();
            }
        }
    };

//    /**
//     *
//     */
//    public void SetTitleBar() {
//        /**
//         * dialog 加载中
//         */
//        LayoutInflater inflater = getLayoutInflater();
//        View dialogView = inflater.inflate(R.layout.loading_spinkit, null);
//        dialog = new Dialog(this, R.style.CustomDialog);
//        dialog.setContentView(dialogView);
//        dialog.setCanceledOnTouchOutside(false);
//    }

    /**
     *
     */
    public void showDialog() {
        if (dialog != null && !dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
